﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics;

namespace Lyon.Updater
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            if (!IsRunAdmin())
            {
                RunAdmin(args);
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            try
            {
                if (args.Length != 1)
                    throw new ArgumentException("");
                Arguments arguments = null;
                try
                {
                    arguments = (Arguments)Arguments.Deserialize(args[0]);
                }
                catch (Exception ex)
                {
                    throw new ArgumentException("", ex);
                }
                if (arguments == null)
                    throw new ArgumentException("");


                MainForm mainForm = new MainForm(arguments);
                //if (arguments.SilentUpdate)
                //    mainForm.CheckUpdate();
                //else
                Application.Run(mainForm);
            }
            catch (ArgumentException)
            {
                MessageBox.Show("请不要执行我！");
            }
        }

        static public bool IsRunAdmin()
        {
            //获得当前登录的Windows用户标示
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
        }
        static void RunAdmin(string[] args)
        {
            Process currentProcess = Process.GetCurrentProcess();
            //创建启动对象
            ProcessStartInfo startInfo = new ProcessStartInfo();
            //设置运行文件
            startInfo.FileName = currentProcess.MainModule.FileName;
            //设置启动参数
            startInfo.Arguments = String.Join(" ", args);
            //设置启动动作,确保以管理员身份运行
            startInfo.Verb = "runas";
            //如果不是管理员，则启动UAC
            System.Diagnostics.Process.Start(startInfo);
            //退出
            currentProcess.Kill();
        }
    }
}
